package com.crowntit.trigger.http;

import com.crowntit.types.sdk.weixin.MessageTextEntity;
import com.crowntit.types.sdk.weixin.SignatureUtil;
import com.crowntit.types.sdk.weixin.XmlUtil;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/weixin/portal/")
public class WeixinPortalController {

    @Value("${weixin.config.originalid}")
    private String originalid;
    @Value("${weixin.config.token}")
    private String token;

    @Resource
    private Cache<String, String> openidToken;

    /**
     * 填写url时验签用
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(value = "receive", produces = "text/plain;charset=utf-8")
    public String validate(@RequestParam(value = "signature", required = false)String signature,
                           @RequestParam(value = "timestamp", required = false)String timestamp,
                           @RequestParam(value = "nonce", required = false)String nonce,
                           @RequestParam(value = "echostr", required = false)String echostr){
        try{
            log.info("微信公众号验签信息开始 [{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
            if (StringUtils.isAnyBlank(signature, nonce, echostr, timestamp)){
                throw new IllegalArgumentException("请求参数非法，请重试");
            }

            boolean check = SignatureUtil.check(token, signature, timestamp, nonce);
            log.info("微信公众号验签信息完成 check：{}", check);
            if (!check){
                return null;
            }
            return echostr;
        } catch (Exception e){
            log.error("微信公众号验签信息失败 [{}, {}, {}, {}]", signature, timestamp, nonce, echostr, e);
            return null;
        }
    }

    /**
     * 接收登录回调
     * @param requestBody 请求体，登录状态信息
     * @param signature 验证用
     * @param nonce 验证用
     * @param timestamp 验证用
     * @param openid 发送者openid
     * @param encryptType 加密类型，当传输模式为安全模式的时候需要根据加密信息解密
     * @param msgSignature
     * @return xml体，登录反馈信息
     */
    @PostMapping(value = "receive", produces = "application/xml; charset=UTF-8")
    public String loginPost(@RequestBody String requestBody,
                            @RequestParam("signature") String signature,
                            @RequestParam("nonce") String nonce,
                            @RequestParam("timestamp") String timestamp,
                            @RequestParam("openid") String openid,
                            @RequestParam(name = "encrypt_type", required = false) String encryptType,
                            @RequestParam(name = "msg_signature", required = false) String msgSignature){
        try{
            log.info("接收微信公众号信息请求{}开始 {}", openid, requestBody);
            MessageTextEntity message = XmlUtil.xmlToBean(requestBody, MessageTextEntity.class);

            if ("event".equals(message.getMsgType()) && "SCAN".equals(message.getEvent())){
                openidToken.put(message.getTicket(), message.getFromUserName());
                return buildMessageTextEntity(message.getFromUserName(), "登录成功");
            }

            log.info("接收微信公众号信息请求{}完成 {}", openid, requestBody);
            return buildMessageTextEntity(openid, "你好, 请扫码登录！");
        } catch (Exception e) {
            log.error("接收微信公众号信息请求{}失败 {}", openid, requestBody, e);
            return "";
        }
    }

    private String buildMessageTextEntity(String openid, String content){
        MessageTextEntity res = new MessageTextEntity();
        res.setMsgType("text");
        res.setContent(content);
        res.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000L));

        res.setFromUserName(originalid);
        res.setToUserName(openid);
        return XmlUtil.beanToXml(res);
    }
}
